# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
import time

import logging

_logger = logging.getLogger(__name__)


class FapiaoPaper(models.Model):
    _inherit = "fp.fapiao.paper"

    def action_ocr(self):
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'in_invoice'),
            ('state', 'in', ['confirmed', 'done']),

        ])

        return self.env['fp.fapiao.ocr'].find_by_fapiao(self2)


class FapiaoOcr(models.Model):
    _name = "fp.fapiao.ocr"
    _inherit = ['fp.fapiao.operate.mixin']
    _description = "Fapiao OCR"
    # _order = 'sequence, name'

    fapiao_id = fields.Many2one(
        domain=[('type', 'in', ['in_invoice'])],
        help="被ocr及ocr结果数据")

    state = fields.Selection(
        selection_add=[
            # ('draft', 'Draft'),  # 初值
            # ('doing', 'Doing'),  # OCR 识别中
            # ('done', 'done'),  # OCR 识别完成 . 末状态  稳定状态
        ],
        string="查验控制", help="查验控制")

    api_ocr_id = fields.Many2one(
        'fp.api.ocr',
        string='Api OCR',
        compute='_compute_api_ocr_id')

    @api.depends('company_id')
    def _compute_api_ocr_id(self):
        for one in self:
            api_company = self.env[
                'fp.api.ocr.company'].search_by_company(one.company_id)

            one.api_ocr_id = api_company.api_ocr_id

    def action_request(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'done'])])

        if self2:
            for one in self2:
                one.state = 'doing'
                # one.fapiao_id.state = 'doing'

            api_ocr_id = self2[0].api_ocr_id
            request_method = api_ocr_id._request_method_get()
            records = request_method(self2)

            for record in records:
                print('action_request', record)
                one = self.browse(record['id'])
                one.write({'state': 'done'})

                def partner_get(saler_or_buyer):
                    if saler_or_buyer == 'saler':
                        fapiao_name = record['saler_name']
                        tin = record['saler_tin']
                        address_phone = record.get('saler_address_phone', '')
                        bank_account = record.get('saler_bank_account', '')
                    else:
                        fapiao_name = record['buyer_name']
                        tin = record['buyer_tin']
                        address_phone = record.get('buyer_address_phone')
                        bank_account = record.get('buyer_bank_account')

                    partner = self.env['fp.partner'].lookup_for_in({
                        'fapiao_name': fapiao_name,
                        'tin': tin,
                        'address_phone': address_phone,
                        'bank_account': bank_account,

                    })

                    return partner.id

                saler_id = partner_get('saler')
                buyer_id = partner_get('buyer')

                values_for_fapiao = {
                    'invoice_type': record['invoice_type'],
                    'taxmachine_code': record['taxmachine_code'],
                    'invoice_code': record['invoice_code'],
                    'invoice_number': record['invoice_number'],
                    'check_code': record.get('check_code'),
                    'note': record['note'],

                    'saler_id': saler_id,
                    'buyer_id': buyer_id,


                    'drawer_name': record['drawer_name'],
                    'payee_name': record['payee_name'],
                    'checker_name': record['checker_name'],

                    'date_fapiao': record['date_fapiao'],

                    'payee_name': record['payee_name'],
                    'payee_name': record['payee_name'],
                    'payee_name': record['payee_name'],

                    'amount_untaxed': record['amount_untaxed'],
                    'amount_tax': record['amount_tax'],
                    'amount_total': record['amount_total'],
                    'cn_amount_total': record['cn_amount_total'],
                }

                print(values_for_fapiao)

                one.fapiao_id.write(values_for_fapiao)


fapiao_data_one = {
    'invoice_type': 'vat_general_e',
    'qrcode': '01,10,011002100111,15159313,76.06,20211105,56183922060040110881,BE26,',
    'invoice_code': '011002100111', 'invoice_number': '15159313', 'date_fapiao': '2021-11-05',
    'amount_untaxed': 76.06, 'amount_tax': 9.49, 'check_code': '56183922060040110881',
    'amount_total': 85.55,
    'saler_name': '北京京东达锐贸易有限公司',
    'saler_tin': '91110112MA01831F9A',
    'buyer_name': '河南晟华工程管理有限公司张家口分公司', 'buyer_tin': '91130703MA0DNJRM8K',
    'company_seal': True, 'kind': '办公', 'taxmachine_code': '661619946800',
    'payee_name': '王陆', 'checker_name': '李思', 'drawer_name': '王梅',
    'province': '北京市', 'city': '', 'service_name': '文具', 'note': '订单号:229485836626',
    'cn_amount_total': '捌拾伍圆伍角伍分', 'id': 2}
